package pixivPc.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;

import pixivPc.MinMazeException;

/**
 * http请求工具
 * 
 * @author wangm
 *
 */
public class RequestUtil {

	/**
	 * Cookie
	 */
	public static CookieManager cookieManager = new CookieManager();

	static {
		cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
		CookieHandler.setDefault(cookieManager);

	}

	/**
	 * 正常code
	 */
	private static final int OK_CODE = 200;

	/**
	 * 跳转code
	 */
	private static final int MOVED_PERMANENTLY_CODE = 301;

	/**
	 * 打开链接
	 * 
	 * @param url
	 *            url
	 * @param sendType
	 *            请求类型 {@link SendType}
	 * @param param
	 *            参数
	 * @param referer
	 *            跳转源url
	 * @return 目标输入流
	 */
	public static InputStream open(String url, SendType sendType, String param, String referer) {
		// post 场合 参数入力用writer
		OutputStreamWriter out = null;
		try {
			HttpURLConnection connection = null;
			// post 场合
			if (sendType.postLike) {
				URL realUrl = new URL(url);
				connection = (HttpURLConnection) realUrl.openConnection();

				// connection setting
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod(sendType.type);

				// connection setting
				connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			} else {
				// get 场合 参数用?连接拼入url
				URL realUrl = new URL(url + "?" + param);
				// open url
				connection = (HttpURLConnection) realUrl.openConnection();
				// connection setting
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			}
			// 跳转源url cookies 设定
			connection.setRequestProperty("Referer", referer);
			connection.setRequestProperty("Cookie", getcookies());
			// X-Requested-With:XMLHttpRequest
			connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

			// connect
			connection.connect();
			if (sendType.postLike) {
				// post 场合 参数通过OutputStreamWriter设定
				// send param
				out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
				out.write(param);
				out.flush();
			}

			if (connection.getResponseCode() == OK_CODE) {
				// 正常
				return connection.getInputStream();

			} else if (connection.getResponseCode() == MOVED_PERMANENTLY_CODE) {
				// 跳转
				String newUrl = connection.getHeaderField("Location");
				System.err.println(newUrl);
				return open(newUrl, sendType, param, referer);
			} else {
				// 异常
				BufferedReader errorIn = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
				String line;
				String result = "";
				while ((line = errorIn.readLine()) != null) {
					result += line;
				}
				errorIn.close();
				throw new MinMazeException(result);
			}

		} catch (Exception e) {
			throw new MinMazeException(e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 读取html
	 * 
	 * @param in
	 *            InputStream
	 * @return html
	 */
	public static String readHtml(InputStream in) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			new MinMazeException(e);
		}
		return sb.toString();
	}

	/**
	 * 请求类型
	 * 
	 * @author wangm
	 *
	 */
	public static enum SendType {
		GET("GET"), POST("POST"), PUT("PUT"), DELETE("DELETE");
		private final String type;
		private final boolean postLike;

		private SendType(String type) {
			this.type = type;
			this.postLike = !type.equals("GET");
		}

	}

	/**
	 * 
	 * @return
	 */
	public static String getcookies() {

		String rslt = "";
		CookieStore store = cookieManager.getCookieStore();

		List<URI> uris = store.getURIs();
		for (URI ur : uris) {
			System.out.println("URI:\t" + ur);
			List<HttpCookie> cookies = store.get(ur);
			for (HttpCookie coo : cookies) {
				if (!rslt.isEmpty()) {
					rslt += "; ";
				}
				rslt += coo.getName() + "=" + coo.getValue();
				System.out.println("#########" + coo.getName() + "\t" + coo.getValue());
			}
		}
		System.out.println("out cook:\t" + rslt);
		return rslt;
	}

}
